package jp.eisbahn.mgapi.api;

import java.util.List;
import java.util.Map;

import jp.eisbahn.mgapi.http.HttpResponse;

/**
 * The exception class thrown when the client catches some error
 * which accessing to API.
 * @author Yoichiro Tanaka
 */
@SuppressWarnings("serial")
public class ApiAccessException extends Exception {

    /** The start position of OAuth error string. */
    private static final int OAUTH_ERROR_START_POS = 13;

    /** The Http response object. */
    private HttpResponse response;

    /**
     * Initialize this instance.
     * @param newResponse The response object.
     */
    public ApiAccessException(final HttpResponse newResponse) {
        super();
        response = newResponse;
    }

    /**
     * Retrieve the response object.
     * @return The response object.
     */
    public final HttpResponse getResponse() {
        return response;
    }

    /**
     * Retrieve the HTTP status code.
     * @return The status code appearing the result.
     */
    public final int getStatusCode() {
        return response.getResponseCode();
    }

    /**
     * Retrieve the status message against the HTTP status code.
     * @return The human readable message.
     */
    public final String getStatusMessage() {
        return response.getResponseMessage();
    }

    /**
     * Retrieve the response body as String.
     * @return The response body string.
     */
    public final String getResponseBody() {
        return response.getResponseBody();
    }

    /**
     * Retrieve the OAuth error message.
     * @return The OAuth error message.
     */
    public final String getOAuthError() {
        Map<String, List<String>> headerMap = response.getHeaderMap();
        if (headerMap != null) {
            List<String> list = headerMap.get("WWW-Authenticate");
            if (list != null && list.size() == 1) {
                String value = list.get(0);
                return value.substring(
                        OAUTH_ERROR_START_POS, value.length() - 1);
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

}
